package com.controller;

import com.exception.ValidateException;
import com.pojo.ClassPropties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 类属性校验在属性上使用@Valid
 *     @Valid
 *     @ApiModelProperty(value = "汽车类")
 *     private Car car;
 * 但是@Valid这个不会对car为null的情况进行校验
 * 比如我只传{"desc":"我是描述"}，此时代码正常执行
 * 所以还需要在属性上加上@NotNull注解
 */
@RestController
@Api(tags = {"测试类属性校验"})
public class ClassProptiesController {

    @PostMapping(value = "/classPropties")
    @ApiOperation(value = "测试类属性校验")
    public ResponseEntity<ClassPropties> classPropties(@RequestBody @Valid ClassPropties classPropties, BindingResult result){
        if (result.hasErrors()){
            throw new ValidateException(result.getFieldErrors());
        }
        return ResponseEntity.ok(classPropties);
    }
}
